<template>
  <div>
    <el-dialog
      v-model="open"
      title="选择流程"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
      :modal="false"
    >
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="流程名称">
          <el-input v-model="queryForm.definitionName" placeholder="请输入流程名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格显示流程列表 -->
      <el-table v-loading="loading" :data="filteredList">
        <el-table-column label="流程名称" align="center" prop="name" />
        <el-table-column>
          <template #default="scope">
            <el-button link type="primary" @click="handleSelect(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        background
        layout="prev, pager, next"
        v-model:page-size="queryForm.pageSize"
        v-model:current-page="queryForm.pageNo"
        :total="total"
        @current-change="getList"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import baseService from "@/service/baseService";

// 查询参数
const queryForm = reactive({
  definitionName: "",
  definitionKey: "",
  active: true,
  pageNo: 1,
  pageSize: 10
});

// 列表相关数据
const total = ref(0);
const loading = ref(true);
const list = ref<any[]>([]);

// 控制弹出框的显示和隐藏
const open = ref(false);

// 初始化方法，打开对话框时调用
const init = () => {
  getList();
  open.value = true;
};

/**
 * 获取流程定义列表
 */
const getList = () => {
  loading.value = true;
  baseService
    .get("/processDefinition/list", queryForm)
    .then((res) => {
      loading.value = false;
      if (res.code === 200) {
        list.value = res.rows;
        total.value = res.total;
      } else {
        list.value = [];
      }
    })
    .catch(() => {
      loading.value = false;
    });
};

/**
 * 重置搜索条件
 */
function handleReset() {
  queryForm.definitionName = "";
  queryForm.pageNo = 1; // 重置页码为第一页
  getList(); // 获取新的数据
}

/**
 * 选择流程行后触发
 * @param row 选择的行数据
 */
function handleSelect(row: any) {
  emit("ok", row); // 通过 emit 事件传递选中的流程
  open.value = false; // 关闭弹出框
}

const emit = defineEmits<{
  (event: "ok", row: any): void;
}>();

// 使用 computed 属性进行筛选
const filteredList = computed(() => {
  return list.value.filter(item => {
    return item.name.includes(queryForm.definitionName);
  });
});

// 对外暴露的方法
defineExpose({
  init
});
</script>

<style scoped></style>